package com.shsubway.activity.manger;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shsubway.R;
import com.shsubway.activity.MainActivity;
import com.shsubway.adapter.ManagementAdapter;
import com.shsubway.base.BaseActivity;
import com.shsubway.model.GroupEntity;
import com.shsubway.model.StaffEntity;
import com.shsubway.utils.Constant;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 员工管理界面 可以对员工进行添加和删除
 */
public class ManagementActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_rec)
    RecyclerView myRec;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    ManagementAdapter managementAdapter;
    Intent intent;
    Bundle bundle;
    StaffEntity staffEntity;
    private int limit = 10;        // 每页的数据是10条
    private int curPage = 0;        // 当前页的编号，从0开始
    List<StaffEntity> staffEntities;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_management);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> {
            setResult(1);
            finish();
        });
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 0;
                addDate();
            }
        });


        myRec.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                bundle.putSerializable(Constant.STAFFENTITY, (StaffEntity) adapter.getItem(position));
                intent.putExtras(bundle);
                intent.putExtra(Constant.TYPE, 1);
                intent.setClass(context, AddStaffActivity.class);
                startActivityForResult(intent, 1);


            }

            @Override
            public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemLongClick(adapter, view, position);
                StaffEntity staffEntity = (StaffEntity) adapter.getItem(position);
                delDialog(staffEntity);
            }
        });

    }


    private void delDialog(StaffEntity staffEntity) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setIcon(R.mipmap.ic_launcher);
        normalDialog.setTitle("提示：");
        normalDialog.setMessage("确定要删除" + staffEntity.getStaff_name() + "吗？");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        staffEntity.delete(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    dialog.dismiss();
                                    toast("删除成功。");
                                    addDate();
                                } else {
                                    toast("删除失败，请重试。");
                                }
                            }
                        });
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    private void initView() {
        setTitleBar(toolbar, "员工列表");
        staffEntities = new ArrayList<>();
        intent = getIntent();
        bundle = intent.getExtras();
        staffEntity = (StaffEntity) bundle.getSerializable(Constant.STAFFENTITY);
        setRefresh(mySwf);
        setRecy(myRec);

        managementAdapter = new ManagementAdapter(R.layout.item_management, staffEntities, context);
        managementAdapter.setEmptyView(emptyView);
        managementAdapter.setOnLoadMoreListener(ManagementActivity.this);
        managementAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        myRec.setAdapter(managementAdapter);
        addDate();
    }

    private void addDate() {

        BmobQuery<StaffEntity> staffEntityBmobQuery = new BmobQuery<>();
        staffEntityBmobQuery.addWhereEqualTo("groupId", staffEntity.getGroupId());
        staffEntityBmobQuery.findObjects(new FindListener<StaffEntity>() {
            @Override
            public void done(List<StaffEntity> list, BmobException e) {
                mySwf.setRefreshing(false);
                if (e == null) {
                    if (curPage == 0) {
                        managementAdapter.setNewData(list);
                    } else {
                        managementAdapter.addData(list);
                    }
                    if (list.size() != 10) {
                        managementAdapter.loadMoreEnd(false);
                    } else {
                        managementAdapter.loadMoreComplete();
                        curPage++;
                    }
                } else {
                    toast("获取配置失败，请稍后重试！");
                }
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        addDate();
    }

    @OnClick(R.id.fab)
    public void onClick() {
        intent.putExtra(Constant.TYPE, 0);
        intent.setClass(context, AddStaffActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        addDate();
    }
}
